﻿using AutoMapper;
using RestApp.UI.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using domain = RestApp.BusinessLogic;
using views = RestApp.UI.Models;

namespace RestApp.UI.Controllers
{
    [Authorize(Roles = "Admin")]
    public class ManagePostsController : Controller
    {
        private IBusinessFactory _factory;
        public ManagePostsController(IBusinessFactory factory)
        {
            _factory = factory;
        }

        public ActionResult List()
        {
            var posts = _factory.JobTitlesLogic.GetAll();
            var mappedPosts = Mapper.Map<IEnumerable<domain.JobTitle>, IEnumerable<views.JobTitle>>(posts);
            return View(mappedPosts);
        }

        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(views.JobTitle job)
        {
            if(!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Пожалуйста, исправьте ошибки");
                return View(job);
            }
            try
            {
                _factory.JobTitlesLogic.Add(job.ToBusinessEntity());
            }
            catch (Exception ex)
            {
                ViewData["error"] = "Произошла ошибка: " + ex.Message;
            }
            return RedirectToAction("List");
        }

        public ActionResult Delete(int id)
        {
            try
            {
                _factory.JobTitlesLogic.RemoveById(id);
            }
            catch (Exception ex)
            {
                TempData["error"] = "Произошла ошибка: " + ex.Message;
            }
            return RedirectToAction("List");
        }

        public ActionResult Edit(int id)
        {
            domain.JobTitle dbEntity = null;
            try
            {
                dbEntity = _factory.JobTitlesLogic.GetById(id);
            }
            catch (Exception ex)
            {
                ViewData["error"] = "Произошла ошибка: " + ex.Message;
            }
            var mappedEntity = Mapper.Map<views.JobTitle>(dbEntity);
            return View(mappedEntity);
        }

        [HttpPost]
        public ActionResult Edit(views.JobTitle jobPost)
        {
            if(!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Пожалуйста, исправьте ошибкаи");
                return View(jobPost);
            }
            try
            {
                _factory.JobTitlesLogic.Edit(jobPost.ToBusinessEntity());
            }
            catch (Exception ex)
            {
                ViewData["error"] = "Произошла ошибка: " + ex.Message;
            }
            return RedirectToAction("List");
        }
    }
}